<template>
  <div class="publish-need">
    <back />
    <el-card class="box-card">
      <el-form ref="formRef" :rules="rules" :model="form" label-width="150px">
        <el-form-item label="需求名称" prop="title">
          <el-input v-model="form.title" placeholder="请输入需求名称"></el-input>
        </el-form-item>
        <el-form-item class="industry" label="行业领域" prop="industrySector">
          <el-select v-model="form.industrySector" multiple clearable placeholder="请选择行业领域">
            <el-option
              v-for="option in industrySectorList"
              :key="option.label"
              :label="option.label"
              :value="option.label"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item class="location" label="所在地" prop="location">
          <el-cascader
            v-model="form.location"
            :props="cityProps"
            :options="cityData"
            placeholder="请选择所在地"
          ></el-cascader>
        </el-form-item>
        <el-form-item class="budget" label="投入预算（万元）" prop="budget">
          <el-input-number
            v-model="form.budget"
            :min="1"
            :max="5000"
            :step="10"
            :disabled="isNotConfirm"
            controls-position="right"
            placeholder="请输入投入预算"
          ></el-input-number>
          <el-checkbox v-model="isNotConfirm">面议</el-checkbox>
        </el-form-item>
        <el-form-item label="需求类型" prop="requirementType">
          <el-radio-group v-model="form.requirementType">
            <el-radio label="设计">设计</el-radio>
            <el-radio label="开发">开发</el-radio>
            <el-radio label="咨询">咨询</el-radio>
            <el-radio label="其他">其他</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item class="deadline" label="截止时间" prop="deadline">
          <el-date-picker
            v-model="form.deadline"
            value-format="YYYY-MM-DD"
            type="date"
            placeholder="请选择截止日期"
            :disabled-date="disabledBeforeDate"
          />
        </el-form-item>
        <el-form-item label="需求描述" prop="valueHtml">
          <div style="border: 1px solid #ccc">
            <Toolbar
              style="border-bottom: 1px solid #ccc"
              :editor="editorRef"
              :defaultConfig="toolbarConfig"
              :mode="mode"
            />
            <Editor
              style="height: 500px; overflow-y: hidden"
              v-model="valueHtml"
              :defaultConfig="editorConfig"
              :mode="mode"
              @onCreated="handleCreated"
            />
          </div>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm">提交审核</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { onBeforeUnmount, ref, shallowRef, reactive, onMounted } from 'vue';
import '@wangeditor/editor/dist/css/style.css'; // 引入 css
import { Editor, Toolbar } from '@wangeditor/editor-for-vue';
import back from '@/components/back/index.vue';
import cityData from '@/data/cityData.json';
import type { FormInstance, FormRules } from 'element-plus';
import DOMPurify from 'dompurify';
// 行业领域数据
import { industrySectorList } from '@/data/industrySector';
import { publishNeed, reqGetDemandDetail, updateDemand } from '@/api/technology-transform';
import { useEditorConfig } from '@/hooks/useEditorConfig';
import type { IToolbarConfig } from '@wangeditor/editor';
import { useRoute, useRouter } from 'vue-router';
import { reqFeedback } from '@/utils/reqFeedback';

// 富文本编辑器
// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef();
const mode = 'default';
const valueHtml = ref('');
const toolbarConfig: Partial<IToolbarConfig> = {};
const { editorConfig } = useEditorConfig();
// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
  const editor = editorRef.value;
  if (editor == null) return;
  editor.destroy();
});
const handleCreated = (editor: any) => {
  editorRef.value = editor; // 记录 editor 实例，重要！
};

const form = ref({
  industrySector: [],
  location: [],
  budget: 10 as any,
  requirementType: '',
  title: '',
  deadline: '',
  // 内容 HTML
  content: '',
});
// 级联选择器
const cityProps = {
  value: 'name', // 指定选项的 值 为选项对象的某个属性值
  label: 'name', // 指定选项 标签 为选项对象的某个属性值
  children: 'children', //指定选项的 子选项 为选项对象的某个属性值
};

// 预算是否确定
const isNotConfirm = ref(false);

// 表单校验
const formRef = ref<FormInstance>();
const rules = reactive<FormRules>({
  title: [
    {
      required: true,
      message: '请选择输入需求名称',
      trigger: 'blur',
    },
  ],
  industrySector: [{ required: true, message: '请输入行业领域', trigger: 'change' }],
  location: [
    {
      required: true,
      message: '请输入选择所在地',
      trigger: 'change',
    },
  ],
  // budget: [
  //   {
  //     required: true,
  //     validator: budgetValidator,
  //     trigger: 'blur',
  //   },
  // ],
  requirementType: [
    {
      required: true,
      message: '请输入需求类型',
      trigger: 'blur',
    },
  ],
  deadline: [
    {
      required: true,
      message: '请选择截止日期',
      trigger: 'change',
    },
  ],
  valueHtml: [
    {
      required: true,
      validator: validateValueHtml,
      trigger: 'blur',
    },
  ],
});
function validateValueHtml(rule: any, value: any, callback: any) {
  if (!valueHtml.value) {
    return callback(new Error('请输入需求描述'));
  }
  // 校验通过
  callback();
}

// 设置不能选择之前的时间
function disabledBeforeDate(date: any) {
  const today = new Date();
  today.setDate(today.getDate());
  return date < today;
}

const router = useRouter();
function submitForm() {
  // 表单提交逻辑
  formRef.value?.validate((valid) => {
    if (valid) {
      form.value.content = DOMPurify.sanitize(valueHtml.value);
      form.value.deadline += ' 23:59:59';
      const requestData = { ...form.value };
      if (isNotConfirm.value) {
        requestData.budget = '面议';
      }
      if (nId.value) {
        // 如果nId.value不为空，则是编辑需求
        updateDemand(requestData).then((res: any) => {
          reqFeedback(res);
        });
      } else {
        // 如果nId.value为空，则是新增需求
        publishNeed(requestData).then((res: any) => {
          reqFeedback(res);
        });
      }
      setTimeout(() => {
        router.replace({ name: 'personalCenterNeeds' });
      }, 500);
    } else {
      console.log('校验失败');
    }
  });
}

// 如果传递了nId，则表明是用户编辑需求，则回显表单信息
const route = useRoute();
const nId = ref('');
onMounted(() => {
  nId.value = route.query.nId as string;
  if (nId.value) {
    getDemandDetail(nId.value);
  }
});
function getDemandDetail(nId: string) {
  reqGetDemandDetail(nId).then((res: any) => {
    if (res.code === 200) {
      form.value = {
        ...res.data,
        budget: 10,
      };
      valueHtml.value = res.data.content;
      const budget = res.data.budget;
      if (budget !== '面议') {
        form.value.budget = budget * 1;
      } else {
        isNotConfirm.value = true;
      }
    }
  });
}
</script>

<style lang="scss" scoped>
.publish-need {
  .box-card {
    margin: 20px;
  }
  .industry :deep(.el-select) {
    width: 40% !important;
  }
  .location :deep(.el-cascader) {
    width: 40% !important;
  }
  .budget :deep(.el-input-number) {
    width: 40% !important;
  }
  .deadline :deep(.el-date-editor) {
    width: 40% !important;
  }
  .el-form-item__label {
    font-weight: bold;
  }

  .el-input-number__decrease,
  .el-input-number__increase {
    color: #666;
  }
  .el-button {
    margin-top: 20px;
  }
}
</style>
